package com.ben.chatroom.session;

import com.ben.chatroom.common.entity.ImNode;
import com.ben.chatroom.distribute.ImWoker;
import com.ben.chatroom.session.dao.SessionCacheDAO;
import com.ben.chatroom.session.dao.UserCacheDAO;
import com.ben.chatroom.session.entity.SessionCache;
import com.ben.chatroom.session.entity.UserCache;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * @author huangyijun
 */
@Slf4j
@Repository
public class SessionManage {


    private static SessionManage singleInstance = null;

    private final UserCacheDAO userCacheDao;
    private final SessionCacheDAO sessionCacheDAO;
    public Map<String, ServerSession> sessionMap = new HashMap<>();

    public SessionManage(SessionCacheDAO sessionCacheDAO, UserCacheDAO userCacheDao) {
        this.sessionCacheDAO = sessionCacheDAO;
        this.userCacheDao = userCacheDao;
    }

    public static SessionManage inst() {
        return singleInstance;
    }

    public static void setSingleInstance(SessionManage singleInstance) {
        SessionManage.singleInstance = singleInstance;
    }

    /**
     * 增加本地会话
     */
    public void addLocalSession(LocalSession session) {
        String sessionId = session.getSessionId();
        sessionMap.put(sessionId, session);

        String userId = session.getUser().getUserId();

        //缓存session到redis
        ImNode node = ImWoker.getInst().getLocalNode();
        SessionCache sessionCache = new SessionCache(userId, node, sessionId);

    }

    //关闭连接
    public void closeSession(ChannelHandlerContext ctx) {
        LocalSession session = ctx.channel().attr(LocalSession.SESSION_KEY).get();

        if (null == session || session.isValid()) {
            log.error("session is null or isvalid");
            return;
        }

        session.close();

        removeSession(session.getSessionId());

        /**
         * 通知其他节点，用户下线
         */
        notifyOtherImNodeOffLine(session);
    }



    /**
     *
     */
    private void notifyOtherImNodeOffLine(LocalSession session) {

    }

    /**
     * @param userId 用户id
     * @return 用户session对象
     */
    public List<ServerSession> getSessionBy(String userId) {
        //从缓存处获取所有保存user和session
        UserCache userCache = userCacheDao.get(userId);

        if (null == userCache) {
            log.info("用户: {}下线了，未在缓存中找到!", userId);
            return Collections.emptyList();
        }

        Map<String, SessionCache> map = userCache.getMap();

        if (map.isEmpty()) {
            log.info("用户：{}下线，没有任何会话！", userId);
            return Collections.emptyList();
        }

        List<ServerSession> serverSessionList = new ArrayList<>();
        map.values().forEach(serverCache -> {
            String sessionId = serverCache.getSessionId();
            if (!sessionMap.containsKey(sessionId)) {
                RemoteSession remoteSession = new RemoteSession(serverCache);
                sessionMap.put(sessionId,remoteSession);
                serverSessionList.add(remoteSession);
            }
            serverSessionList.add(sessionMap.get(sessionId));
        });

        return serverSessionList;
    }

    /**
     * 删除会话
     */
    public void removeSession(String sessionId) {
        if(sessionMap.containsKey(sessionId)) {
            return;
        }
        ServerSession session = sessionMap.get(sessionId);
        String userId = session.getUserId();



    }
}
